using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using FlickrNet;
using WhsPhotoUpload.Helpers;

namespace Microsoft.HomeServer.HomeServerConsoleTab.WhsPhotoUploadTab
{
    public partial class MainTabPanel : UserControl
    {
        // This is the default "start" paths for configuring your Photo and Uploaded Folder
        // These settings are used by the folder browser control
        private string defaultPhotoFolder = @"d:\shares";
        private string defaultUploaderAppFolder = @"c:\program files";

        // This flag tracks if we're in the midst of a manual photo upload process
        // This prevents two uploads from happening at once
        // TODO: Prevention of two uploads should be placed in Uploader logic
        private bool manualUploadInProgress = false;

        public MainTabPanel()
        {
            // Normal winform stuff
            InitializeComponent();
            

            // We now retrieve saved app settings from registry
            reloadSettings();

            //// Some vanity related settings to make the UI pretty
            //ResetUiLayout();
            //splitContainer1.IsSplitterFixed = true;


        }

        #region -- Application Configuration Settings Related ---------

        private void lbRefreshSettings_Click(object sender, EventArgs e)
        {
            reloadSettings();
            MessageBox.Show("Settings Refreshed", "WHS Photo Uploader", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnSelectPickupFolder_Click(object sender, EventArgs e)
        {
            folderBrowser.SelectedPath = defaultPhotoFolder;

            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
                tbPickUpFolder.Text = folderBrowser.SelectedPath + @"\";
            }

            // Save Setting
            RegistryTools.SetAppSetting(
                RegistryTools.WhsPhotoUploadSettings.PhotoPickupFolder,
                tbPickUpFolder.Text);

        }

        private void btnSelectUploadedFolder_Click(object sender, EventArgs e)
        {
            folderBrowser.SelectedPath = defaultPhotoFolder;

            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
                tbUploadedFolder.Text = folderBrowser.SelectedPath + @"\";
            }

            // Save Setting
            RegistryTools.SetAppSetting(
                RegistryTools.WhsPhotoUploadSettings.PhotoFinishedFolder,
                tbUploadedFolder.Text);

        }

        private void btnSelectUploaderPath_Click(object sender, EventArgs e)
        {
            folderBrowser.SelectedPath = defaultUploaderAppFolder;

            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
                tbUploaderAppPath.Text = folderBrowser.SelectedPath + @"\";
            }

            // Save Setting
             RegistryTools.SetAppSetting(
                RegistryTools.WhsPhotoUploadSettings.UploaderRootPath,
                tbUploaderAppPath.Text);

        }

        private void reloadSettings()
        {
            // Check for the Flickr token to see if the account has been linked yet
            CheckFlickrAccountLinkage();

            // Get Folder Settings
            tbPickUpFolder.Text = RegistryTools.GetAppSetting(
                RegistryTools.WhsPhotoUploadSettings.PhotoPickupFolder);
            tbUploadedFolder.Text = RegistryTools.GetAppSetting(
                RegistryTools.WhsPhotoUploadSettings.PhotoFinishedFolder);

            // Get Application Settings
            tbUploaderAppPath.Text = RegistryTools.GetAppSetting(
                RegistryTools.WhsPhotoUploadSettings.UploaderRootPath);
        }
        #endregion

        #region -- UI Related Methods ---------------------------------
        private void ResetUiLayout()
        {
            // Some UI Layout
            splitContainer1.SplitterDistance = 277;
        }



        private void MainTabPanel_Load(object sender, EventArgs e)
        {
            // The UI has now been loaded by WHS Console, we now reset the UI
            ResetUiLayout();
        }
        #endregion

        #region -- AutoLog Refresh and Timer Related ------------------

        private void lbAutoRefresh_Click(object sender, EventArgs e)
        {
            if (timerRefreshActivityView.Enabled)
            {
                // Timer is on... let's stop it
                StopLogAutoRefresh();
            }
            else
            {
                // Timer is off... let's start it
                StartLogAutoRefresh();
            }
        }
        private void StartLogAutoRefresh()
        {
            // Stop the timer
            timerRefreshActivityView.Start();

            // Reset the UI
            lbAutoRefresh.Text = "Stop Log Auto Refresh";
        }

        private void StopLogAutoRefresh()
        {
            // Stop the timer
            timerRefreshActivityView.Stop();

            // Reset the UI
            lbAutoRefresh.Text = "Start Log Auto Refresh";
        }

        private void timerRefreshActivityView_Tick(object sender, EventArgs e)
        {
            // The log database is kept in the same place as the uploader
            // We rebuild the connection string to pull data from that new area
            string connString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"{0}\\appDb.mdb\"", tbUploaderAppPath.Text);

            // Check to see if we can find the database
            if (!System.IO.File.Exists(string.Format("{0}\\appDb.mdb", tbUploaderAppPath.Text)))
            {
                MessageBox.Show(string.Format("I'm unable to find the appDb.mdb file in {0}.  Double check the specified UPLOADER APP path.", tbUploaderAppPath.Text), "WHS Photo Uploader", MessageBoxButtons.OK, MessageBoxIcon.Error);
                timerRefreshActivityView.Stop();
            }
            else
            {
                // Found the database, now start refresh
                refreshActivityDataGrid(connString);
            }
        }

        private void refreshActivityDataGrid(string connString)
        {
            try
            {
                appDbDataSetTableAdapters.ActivityLogTableAdapter myAdapter = new appDbDataSetTableAdapters.ActivityLogTableAdapter();
                appDbDataSet.ActivityLogDataTable myTable = new appDbDataSet.ActivityLogDataTable();

                myAdapter.Connection = new System.Data.OleDb.OleDbConnection(connString);

                myAdapter.Fill(myTable);

                dgActivityLog.DataSource = myTable;

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.ToString(), "WHS Photo Uploader", MessageBoxButtons.OK, MessageBoxIcon.Error);
                dgActivityLog.DataSource = "";

                // Whoops.  An error occured.  I'll stop the log auto-refresh
                StopLogAutoRefresh();
            }
        }
        #endregion

        #region -- "Kick Up the Uploader" Methods ---------------------

        private void lbManualStart_Click(object sender, EventArgs e)
        {
            // We check to see if a manual upload is currently underway
            if (!manualUploadInProgress)
            {
                // Good, let's set the "we're uploading" flag before we start
                manualUploadInProgress = true;

                // Are we currently auto refreshing?  Check the timer.
                if (!timerRefreshActivityView.Enabled)
                {
                    // Nope.  We are not auto refreshing.  Let's kick on the timer.
                    StartLogAutoRefresh();
                }

                try
                {
                    // We build the path to the uploader program
                    string pathOfUploader = string.Format("{0}\\WhsPhotoUpload.Uploader.exe", tbUploaderAppPath.Text);

                    // We now kick off the program
                    System.Diagnostics.Process.Start(pathOfUploader);
                }
                catch (Exception ee)
                {
                    MessageBox.Show(string.Format("Error while executing uploader:\r\n{0}", ee.ToString()), "WHS Photo Uploader", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    // Error?  We better stop the timer and update the text of the auto-fresh label
                    StopLogAutoRefresh();
                }
                finally
                {
                    // We're done so let's set the flag back
                    manualUploadInProgress = false;
                }
            }
        }
        #endregion

        #region -- Linking Flickr Account to App Related --------------

        string tempFrob;
        Flickr flickr;

        string apikey = RegistryTools.GetAppSetting(RegistryTools.WhsPhotoUploadSettings.FlickrApplicationKey);
        string sharedsecret = RegistryTools.GetAppSetting(RegistryTools.WhsPhotoUploadSettings.FlickrSharedSecret);


        private void btnLinkAccount_Click(object sender, EventArgs e)
        {
            Auth auth;
            flickr = new Flickr(apikey, sharedsecret);
            tempFrob = flickr.AuthGetFrob();
            string flickrUrl = flickr.AuthCalcUrl(tempFrob, AuthLevel.Write);
            Process p = new Process();
            p = Process.Start("IExplore.exe", flickrUrl);

            p.WaitForExit();
            try
            {
                auth = flickr.AuthGetToken(tempFrob);
                flickr.AuthToken = auth.Token;
                RegistryTools.SetAppSetting(RegistryTools.WhsPhotoUploadSettings.FlickrToken, flickr.AuthToken);
                MessageBox.Show("Linking is successful. You can start using Windows Home Server to upload to flickr now.");
            }
            catch
            {
                MessageBox.Show("Your linking is not successful. Please try again and ensure that you have login to yahoo/flickr successfully.");
            }

            CheckFlickrAccountLinkage();
        }

        private void CheckFlickrAccountLinkage()
        {
            string currentFlickrToken = RegistryTools.GetAppSetting(RegistryTools.WhsPhotoUploadSettings.FlickrToken);

            if (currentFlickrToken == null || currentFlickrToken.Trim().Length == 0)
            {
                tbAccountStatus.ForeColor = Color.Red;
                tbAccountStatus.Text = "This application is not linked.  Click the bottom button to link this application.";
            }
            else
            {
                tbAccountStatus.ForeColor = Color.LightGreen;
                tbAccountStatus.Text = string.Format("LINKED.  Token = {0}", currentFlickrToken);
            }
        }
        #endregion

    }
}
